<template>
  <q-input
    dense
    outlined
    v-model.lazy="myColor"
  >
    <template v-slot:append>
      <q-icon name="colorize" class="cursor-pointer">
        <q-popup-proxy transition-show="scale" transition-hide="scale">
          <q-color v-model="myColor" format-model="hex"/>
        </q-popup-proxy>
      </q-icon>
    </template>
  </q-input>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, computed } from  'vue';
import { colors } from 'quasar';
import { isObjectEmpty } from 'src/util/utils';

export default defineComponent({
  name: 'ColorInput',
  props: {
    color: {
      type: String,
      default: () => {
        return '#0ffcc0'
      }
    }
  },

  emits: ['update:color'],
  setup (props, context) {
    //解构
    const {
      color
    } = toRefs(props);

    // 引入quasar颜色转换函数
    const {
      getPaletteColor,
      textToRgb,
      rgbToHex
    } = colors;

    // 响应对象
    let myColor = computed({
      get: () => {
        if (!isObjectEmpty(color.value)) {
          if (color.value.startsWith('#')) {
            return color.value;
          } else if (color.value.startsWith('rgb')) {
            let c = textToRgb(color.value);
            return rgbToHex(c);
          } else {
            return getPaletteColor(color.value);
          }
        } else {
          return '#4badc6';
        }
      },
      set: (c: string) => {
        context.emit('update:color', c);
      }
    });

    return {
      myColor
    };
  }
});

</script>

<style lang="scss" scoped>

</style>
